/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ResultFrame.java
 *
 * Created on 16.12.2011, 18:17:00
 */
package de.aeo.bll;

import java.awt.Color;
import java.awt.Component;
import java.awt.Rectangle;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

/**
 * @author Frederic Branczyk & Robert Piwonski
 */
public class ResultFrame extends javax.swing.JFrame {
    
    Algorithm a;

    /** Creates new form ResultFrame */
    public ResultFrame(Algorithm a) {
        this.a = a;
        initComponents();
        this.update();
        this.jTable1.setDefaultRenderer(Object.class, new MyTableCellRenderer());
        this.jTable1.setAutoCreateRowSorter(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jScrollPane3 = new javax.swing.JScrollPane();
        jList3 = new javax.swing.JList();
        jScrollPane4 = new javax.swing.JScrollPane();
        jList4 = new javax.swing.JList();
        jScrollPane5 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jScrollPane1.setViewportView(jList1);

        jScrollPane2.setViewportView(jList2);

        jScrollPane3.setViewportView(jList3);

        jScrollPane4.setViewportView(jList4);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setRowHeight(32);
        jScrollPane5.setViewportView(jTable1);

        jButton1.setText(this.a.getLanguageString("save"));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 826, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE))
                    .addComponent(jButton1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 198, Short.MAX_VALUE)
                    .addComponent(jScrollPane2)
                    .addComponent(jScrollPane3)
                    .addComponent(jScrollPane4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 261, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            this.a.exportResultData();
            JOptionPane.showMessageDialog(this, this.a.getLanguageString("doneMsg"), this.a.getLanguageString("titleSuccess"), 1);
            System.exit(0);
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), this.a.getLanguageString("titleWarning"), 0);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), this.a.getLanguageString("titleWarning"), 0);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void update() {
        ArrayList<ArrayList<Course>> list = a.getSchedule();
        DefaultListModel dlm1 = new DefaultListModel();
        for(Course c:list.get(0)) {
            dlm1.add(dlm1.getSize(), c.getName()+" ("+c.getSubject().getAbbreviation()+c.getSubject().getPeriodAbbreviation()+") - "+c.getStudentList().size());
        }
        this.jList1.setModel(dlm1);
        DefaultListModel dlm2 = new DefaultListModel();
        for(Course c:list.get(1)) {
            dlm2.add(dlm2.getSize(), c.getName()+" ("+c.getSubject().getAbbreviation()+c.getSubject().getPeriodAbbreviation()+") - "+c.getStudentList().size());
        }
        this.jList2.setModel(dlm2);
        DefaultListModel dlm3 = new DefaultListModel();
        for(Course c:list.get(2)) {
            dlm3.add(dlm3.getSize(), c.getName()+" ("+c.getSubject().getAbbreviation()+c.getSubject().getPeriodAbbreviation()+") - "+c.getStudentList().size());
        }
        this.jList3.setModel(dlm3);
        DefaultListModel dlm4 = new DefaultListModel();
        for(Course c:list.get(3)) {
            dlm4.add(dlm4.getSize(), c.getName()+" ("+c.getSubject().getAbbreviation()+c.getSubject().getPeriodAbbreviation()+") - "+c.getStudentList().size());
        }
        this.jList4.setModel(dlm4);
        
        ArrayList<Student> list1 = new ArrayList<Student>(this.a.getStudentList());
        int i = 0;
        Object[][] data = new Object[list1.size()][8];
        for(Student s:list1) {
            Object[] str = {null, null, null, null, null, null, null, null};
            str[0] = s.getLastname();
            str[1] = s.getFirstname();
            str[2] = s.getcClass();
            if(s.getCourseList()[0]!=null)
                str[3] = s.getCourseList()[0].getName()+" ("+s.getCourseList()[0].getSubject().getAbbreviation()+s.getCourseList()[0].getSubject().getPeriodAbbreviation()+")";
            else
                str[3] = this.a.getLanguageString("<none>");
            if(s.getCourseList()[1]!=null)
                str[4] = s.getCourseList()[1].getName()+" ("+s.getCourseList()[1].getSubject().getAbbreviation()+s.getCourseList()[1].getSubject().getPeriodAbbreviation()+")";
            else
                str[4] = this.a.getLanguageString("<none>");
            if(s.getCourseList()[2]!=null)
                str[5] = s.getCourseList()[2].getName()+" ("+s.getCourseList()[2].getSubject().getAbbreviation()+s.getCourseList()[2].getSubject().getPeriodAbbreviation()+")";
            else
                str[5] = this.a.getLanguageString("<none>");
            if(s.getCourseList()[3]!=null)
                str[6] = s.getCourseList()[3].getName()+" ("+s.getCourseList()[3].getSubject().getAbbreviation()+s.getCourseList()[3].getSubject().getPeriodAbbreviation()+")";
            else
                str[6] = this.a.getLanguageString("<none>");
            
            str[7] = s;
            
            data[i] = str;
            
            i++;
        }
        
        DefaultTableModel dtm1 = new DefaultTableModel(data, this.getHeader()) {
            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;
            }
        };
        
        this.jTable1.setModel(dtm1);
        this.jTable1.getColumnModel().getColumn(this.jTable1.getColumnCount()-1).setMinWidth(0);
        this.jTable1.getColumnModel().getColumn(this.jTable1.getColumnCount()-1).setMaxWidth(0);
        this.jTable1.getColumnModel().getColumn(this.jTable1.getColumnCount()-1).setWidth(0);
        this.jTable1.getColumnModel().getColumn(this.jTable1.getColumnCount()-1).setResizable(false);
        this.jTable1.getColumnModel().getColumn(this.jTable1.getColumnCount()-1).setPreferredWidth(0);
    }
    
    public Object[] getHeader() {
        String[] header = {
            this.a.getLanguageString("lastname"),
            this.a.getLanguageString("firstname"),
            this.a.getLanguageString("class"),
            this.a.getLanguageString("course")+" 1",
            this.a.getLanguageString("course")+" 2",
            this.a.getLanguageString("course")+" 3",
            this.a.getLanguageString("course")+" 4",
            "invis"
        };
        return header;
    }
    
    public void updateObject() {
        ((DefaultTableModel) this.jTable1.getModel()).setColumnIdentifiers(this.getHeader());
        this.a.getLanguageString("save");
        this.update();
    }
    
        /*
     * %W% %E%
     *
     * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
     * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
     */




    /**
     * The standard class for rendering (displaying) individual cells
     * in a <code>JTable</code>.
     * <p>
     *
     * <strong><a name="override">Implementation Note:</a></strong>
     * This class inherits from <code>JLabel</code>, a standard component class. 
     * However <code>JTable</code> employs a unique mechanism for rendering
     * its cells and therefore requires some slightly modified behavior
     * from its cell renderer.  
     * The table class defines a single cell renderer and uses it as a 
     * as a rubber-stamp for rendering all cells in the table; 
     * it renders the first cell,
     * changes the contents of that cell renderer, 
     * shifts the origin to the new location, re-draws it, and so on.
     * The standard <code>JLabel</code> component was not
     * designed to be used this way and we want to avoid 
     * triggering a <code>revalidate</code> each time the
     * cell is drawn. This would greatly decrease performance because the
     * <code>revalidate</code> message would be
     * passed up the hierarchy of the container to determine whether any other
     * components would be affected.  
     * As the renderer is only parented for the lifetime of a painting operation
     * we similarly want to avoid the overhead associated with walking the
     * hierarchy for painting operations.
     * So this class
     * overrides the <code>validate</code>, <code>invalidate</code>,
     * <code>revalidate</code>, <code>repaint</code>, and
     * <code>firePropertyChange</code> methods to be 
     * no-ops and override the <code>isOpaque</code> method solely to improve
     * performance.  If you write your own renderer,
     * please keep this performance consideration in mind.
     * <p>
     *
     * <strong>Warning:</strong>
     * Serialized objects of this class will not be compatible with
     * future Swing releases. The current serialization support is
     * appropriate for short term storage or RMI between applications running
     * the same version of Swing.  As of 1.4, support for long term storage
     * of all JavaBeans<sup><font size="-2">TM</font></sup>
     * has been added to the <code>java.beans</code> package.
     * Please see {@link java.beans.XMLEncoder}.
     *
     * @version %I% %G%
     * @author Philip Milne 
     * @see JTable
     */
    class MyTableCellRenderer extends JLabel
        implements TableCellRenderer, Serializable
    {

       /**
        * An empty <code>Border</code>. This field might not be used. To change the
        * <code>Border</code> used by this renderer override the 
        * <code>getTableCellRendererComponent</code> method and set the border
        * of the returned component directly.
        */
        private final Border SAFE_NO_FOCUS_BORDER = new EmptyBorder(1, 1, 1, 1);
        private final Border DEFAULT_NO_FOCUS_BORDER = new EmptyBorder(1, 1, 1, 1);
        protected Border noFocusBorder = DEFAULT_NO_FOCUS_BORDER;

        // We need a place to store the color the JLabel should be returned 
        // to after its foreground and background colors have been set 
        // to the selection background color. 
        // These ivars will be made protected when their names are finalized. 
        private Color unselectedForeground; 
        private Color unselectedBackground; 

        /**
         * Creates a default table cell renderer.
         */
        public MyTableCellRenderer() {
            super();
            setOpaque(true);
            setBorder(getNoFocusBorder());
            setName("Table.cellRenderer");
        }

        private Border getNoFocusBorder() {
            Border border = DefaultLookup.getBorder(this, ui, "Table.cellNoFocusBorder");
            if (System.getSecurityManager() != null) {
                if (border != null) return border;
                return SAFE_NO_FOCUS_BORDER;
            } else if (border != null) {
                if (noFocusBorder == null || noFocusBorder == DEFAULT_NO_FOCUS_BORDER) {
                    return border;
                }
            }
            return noFocusBorder;
        }

        /**
         * Overrides <code>JComponent.setForeground</code> to assign
         * the unselected-foreground color to the specified color.
         * 
         * @param c set the foreground color to this value
         */
            @Override
        public void setForeground(Color c) {
            super.setForeground(c); 
            unselectedForeground = c; 
        }

        /**
         * Overrides <code>JComponent.setBackground</code> to assign
         * the unselected-background color to the specified color.
         *
         * @param c set the background color to this value
         */
            @Override
        public void setBackground(Color c) {
            super.setBackground(c); 
            unselectedBackground = c; 
        }

        /**
         * Notification from the <code>UIManager</code> that the look and feel
         * [L&F] has changed.
         * Replaces the current UI object with the latest version from the 
         * <code>UIManager</code>.
         *
         * @see JComponent#updateUI
         */
            @Override
        public void updateUI() {
            super.updateUI(); 
            setForeground(null);
            setBackground(null);
        }

        // implements javax.swing.table.TableCellRenderer
        /**
         *
         * Returns the default table cell renderer.
         * <p>
         * During a printing operation, this method will be called with
         * <code>isSelected</code> and <code>hasFocus</code> values of
         * <code>false</code> to prevent selection and focus from appearing
         * in the printed output. To do other customization based on whether
         * or not the table is being printed, check the return value from
         * {@link javax.swing.JComponent#isPaintingForPrint()}.
         *
         * @param table  the <code>JTable</code>
         * @param value  the value to assign to the cell at
         *			<code>[row, column]</code>
         * @param isSelected true if cell is selected
         * @param hasFocus true if cell has focus
         * @param row  the row of the cell to render
         * @param column the column of the cell to render
         * @return the default table cell renderer
         * @see javax.swing.JComponent#isPaintingForPrint()
         */
            @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                              boolean isSelected, boolean hasFocus, int row, int column) {

            Color fg = null;
            Color bg = null;

            JTable.DropLocation dropLocation = table.getDropLocation();
            if (dropLocation != null
                    && !dropLocation.isInsertRow()
                    && !dropLocation.isInsertColumn()
                    && dropLocation.getRow() == row
                    && dropLocation.getColumn() == column) {

                fg = DefaultLookup.getColor(this, ui, "Table.dropCellForeground");
                bg = DefaultLookup.getColor(this, ui, "Table.dropCellBackground");

                isSelected = true;
            }
            
            Student s = (Student) jTable1.getValueAt(row, jTable1.getColumnCount()-1);
            
            if (isSelected) {
                super.setForeground(fg == null ? table.getSelectionForeground()
                                               : fg);
                super.setBackground(bg == null ? table.getSelectionBackground()
                                               : bg);
            }else if(s.getState()==2) {
                Color co = new Color(255, 153, 173);
                super.setBackground(co);
            }else if(s.getState()==1){
                Color co = new Color(153, 230, 255);
                super.setBackground(co);
            }else {
                Color background = unselectedBackground != null
                                        ? unselectedBackground
                                        : table.getBackground();
                if (background == null || background instanceof javax.swing.plaf.UIResource) {
                    Color alternateColor = DefaultLookup.getColor(this, ui, "Table.alternateRowColor");
                    if (alternateColor != null && row % 2 == 0)
                        background = alternateColor;
                }
                super.setForeground(unselectedForeground != null
                                        ? unselectedForeground
                                        : table.getForeground());
                super.setBackground(background);
            }

            setFont(table.getFont());

            if (hasFocus) {
                Border border = null;
                if (isSelected) {
                    border = DefaultLookup.getBorder(this, ui, "Table.focusSelectedCellHighlightBorder");
                }
                if (border == null) {
                    border = DefaultLookup.getBorder(this, ui, "Table.focusCellHighlightBorder");
                }
                setBorder(border);

                if (!isSelected && table.isCellEditable(row, column)) {
                    Color col;
                    col = DefaultLookup.getColor(this, ui, "Table.focusCellForeground");
                    if (col != null) {
                        super.setForeground(col);
                    }
                    col = DefaultLookup.getColor(this, ui, "Table.focusCellBackground");
                    if (col != null) {
                        super.setBackground(col);
                    }
                }
            } else {
                setBorder(getNoFocusBorder());
            }

            setValue(value); 

            return this;
        }

        /*
         * The following methods are overridden as a performance measure to 
         * to prune code-paths are often called in the case of renders
         * but which we know are unnecessary.  Great care should be taken
         * when writing your own renderer to weigh the benefits and 
         * drawbacks of overriding methods like these.
         */

        /**
         * Overridden for performance reasons.
         * See the <a href="#override">Implementation Note</a> 
         * for more information.
         */
            @Override
        public boolean isOpaque() { 
            Color back = getBackground();
            Component p = getParent(); 
            if (p != null) { 
                p = p.getParent(); 
            }

            // p should now be the JTable. 
            boolean colorMatch = (back != null) && (p != null) && 
                back.equals(p.getBackground()) && 
                            p.isOpaque();
            return !colorMatch && super.isOpaque(); 
        }

        /**
         * Overridden for performance reasons.
         * See the <a href="#override">Implementation Note</a> 
         * for more information.
         *
         * @since 1.5
         */
            @Override
        public void invalidate() {}

        /**
         * Overridden for performance reasons.
         * See the <a href="#override">Implementation Note</a> 
         * for more information.
         */
            @Override
        public void validate() {}

        /**
         * Overridden for performance reasons.
         * See the <a href="#override">Implementation Note</a> 
         * for more information.
         */
            @Override
        public void revalidate() {}

        /**
         * Overridden for performance reasons.
         * See the <a href="#override">Implementation Note</a> 
         * for more information.
         */
            @Override
        public void repaint(long tm, int x, int y, int width, int height) {}

        /**
         * Overridden for performance reasons.
         * See the <a href="#override">Implementation Note</a> 
         * for more information.
         */
            @Override
        public void repaint(Rectangle r) { }

        /**
         * Overridden for performance reasons.
         * See the <a href="#override">Implementation Note</a> 
         * for more information.
         *
         * @since 1.5
         */
            @Override
        public void repaint() {
        }

        /**
         * Overridden for performance reasons.
         * See the <a href="#override">Implementation Note</a> 
         * for more information.
         */
            @Override
        protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {	
            // Strings get interned...
            if ("text".equals(propertyName)
                    || "labelFor".equals(propertyName)
                    || "displayedMnemonic".equals(propertyName)
                    || (("font".equals(propertyName) || "foreground".equals(propertyName))
                        && oldValue != newValue
                        && getClientProperty(javax.swing.plaf.basic.BasicHTML.propertyKey) != null)) {

                super.firePropertyChange(propertyName, oldValue, newValue);
            }
        }

        /**
         * Overridden for performance reasons.
         * See the <a href="#override">Implementation Note</a> 
         * for more information.
         */
            @Override
        public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { }


        /**
         * Sets the <code>String</code> object for the cell being rendered to
         * <code>value</code>.
         * 
         * @param value  the string value for this cell; if value is
         *		<code>null</code> it sets the text value to an empty string
         * @see JLabel#setText
         * 
         */
        protected void setValue(Object value) {
            setText((value == null) ? "" : value.toString());
        }


        /**
         * A subclass of <code>DefaultTableCellRenderer</code> that
         * implements <code>UIResource</code>.
         * <code>DefaultTableCellRenderer</code> doesn't implement
         * <code>UIResource</code>
         * directly so that applications can safely override the
         * <code>cellRenderer</code> property with
         * <code>DefaultTableCellRenderer</code> subclasses.
         * <p>
         * <strong>Warning:</strong>
         * Serialized objects of this class will not be compatible with
         * future Swing releases. The current serialization support is
         * appropriate for short term storage or RMI between applications running
         * the same version of Swing.  As of 1.4, support for long term storage
         * of all JavaBeans<sup><font size="-2">TM</font></sup>
         * has been added to the <code>java.beans</code> package.
         * Please see {@link java.beans.XMLEncoder}.
         */
        public class UIResource extends MyTableCellRenderer 
            implements javax.swing.plaf.UIResource
        {
        }

    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JList jList1;
    private javax.swing.JList jList2;
    private javax.swing.JList jList3;
    private javax.swing.JList jList4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
